//
//  JJAssetDeduplicator.swift
//  JJAlbum
//
//  Created by 吴梓杭 on 2025/10/14.
//

import Photos
import CommonCrypto

class JJAssetDeduplicator_Abandon {
    public var uploadedRecords = Set<String>()
    private let lock = NSLock()
    
    enum CheckLevel {
        case quick      // 仅检查localIdentifier
        case standard   // 检查基础元数据
        case strict     // 检查内容哈希
    }
    
    func shouldUpload(_ asset: PHAsset, level: CheckLevel = .standard) -> Bool {
        // 确保在主线程访问PHAsset属性
        if Thread.isMainThread {
            return performCheck(asset: asset, level: level)
        } else {
            var result = false
            DispatchQueue.main.sync {
                result = performCheck(asset: asset, level: level)
            }
            return result
        }
    }
    
    private func performCheck(asset: PHAsset, level: CheckLevel) -> Bool {
        lock.lock()
        defer { lock.unlock() }
        
        let currentID = generateUniqueID(asset: asset, level: level)
        print(currentID)
        return !uploadedRecords.contains(currentID)
    }
    
    private func generateUniqueID(asset: PHAsset, level: CheckLevel) -> String {
        switch level {
        case .quick:
            return asset.localIdentifier
            
        case .standard:
            let size = asset.pixelWidth * asset.pixelHeight
            let date = asset.creationDate?.timeIntervalSince1970 ?? 0
            return "\(asset.localIdentifier)-\(size)-\(date)"
            
        case .strict:
            let hash = generateContentHash(asset) ?? "nil"
            return "\(asset.localIdentifier)-\(hash)"
        }
    }
    
    private func generateContentHash(_ asset: PHAsset) -> String? {
        var hash: String?
        let semaphore = DispatchSemaphore(value: 0)
        
        DispatchQueue.main.async {
            let options = PHImageRequestOptions()
            options.isSynchronous = true
            options.deliveryMode = .highQualityFormat
            options.isNetworkAccessAllowed = true
            
            PHImageManager.default().requestImageDataAndOrientation(
                for: asset,
                options: options
            ) { data, _, _, _ in
                hash = data?.sha256()
                semaphore.signal()
            }
        }
        
        semaphore.wait()
        return hash
    }
}

extension Data {
    func sha256() -> String {
        var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
        withUnsafeBytes {
            _ = CC_SHA256($0.baseAddress, CC_LONG(count), &hash)
        }
        return hash.map { String(format: "%02x", $0) }.joined()
    }
}
